package com.gdyx.app.web.web;

import com.gdyx.app.web.annotation.Authorisation;
import com.gdyx.app.web.model.MpsCheckOrg;
import com.gdyx.app.web.model.MpsOrg;
import com.gdyx.app.web.model.MpsOrgUser;
import com.gdyx.app.web.model.MpsUser;
import com.gdyx.app.web.svc.*;
import com.gdyx.app.web.util.Condition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RequestMapping("/MpsOrg")
@Controller
public class MpsOrgController extends BaseController {
    @Autowired
    HttpServletRequest request;
    @Autowired
    MpsOrgSvc mpsOrgSvc;
    @Autowired
    MpsRoleSvc mpsRoleSvc;
    @Autowired
    MpsDeptSvc mpsDeptSvc;
    @Autowired
    MpsOrgUserSvc mpsOrgUserSvc;
    @Autowired
    MpsUserSvc mpsUserSvc;

    @Authorisation(value = "/MpsOrg/goMpsOrgList")
    @GetMapping("/goMpsOrgList")
    public ModelAndView goMpsOrgList(@ModelAttribute("respMsg") String respMsg) {
        ModelAndView view = new ModelAndView();
        Map<String, Object> map = new HashMap<>();
        List<MpsOrg> resultRole = mpsOrgSvc.findMpsOrgs(map);
        view.addObject("respMsg", respMsg);
        view.addObject("MpsOrgList", resultRole);
        view.setViewName("MpsOrgList");
        return view;
    }

    @Authorisation(value = "/MpsOrg/Update")
    @GetMapping("/goMpsOrgEdit")
    public ModelAndView goMpsOrgEdit(@ModelAttribute("respMsg") String respMsg, @RequestParam("id") String id) {
        ModelAndView view = new ModelAndView();
        MpsOrg findMpsOrg = mpsOrgSvc.findMpsOrgById(id);
        if (null == findMpsOrg) {
            view.addObject("respMsg", "查询机构不存在");
            view.setViewName("redirect:/MpsOrg/goMpsOrgList");
            return view;
        } else {
            view.addObject("M_I", findMpsOrg);
            view.addObject("respMsg", respMsg);
            view.setViewName("MpsOrgEdit");
            return view;
        }
    }

    /**
     * 前往用户申请审核页面
     * @param respMsg
     * @return
     */
    @GetMapping("/goMpsCheckUserList")
    public ModelAndView goMpsCheckUserList(@ModelAttribute("respMsg") String respMsg) {
        MpsUser mpsUser = (MpsUser) request.getSession().getAttribute("ADMIN_SESSION");
        ModelAndView view = new ModelAndView();
        //当前用户下的所有机构信息
        List<MpsOrgUser> mpsOrgUsersByUid = mpsOrgUserSvc.findMpsOrgUsersByUid(mpsUser.getId());
        //封装返回申请信息
        List<MpsCheckOrg> chkList=new ArrayList<>();
        //遍历机构
        for (MpsOrgUser mpsOrgUser : mpsOrgUsersByUid) {
            //获得机构下的所有关联用户数据
            List<MpsOrgUser> mpsOrgUsersByOid = mpsOrgUserSvc.findMpsOrgUsersByOid(mpsOrgUser.getOrgId());
            for (MpsOrgUser orgUser : mpsOrgUsersByOid) {
                //封装
                if("2".equals(String.valueOf(orgUser.getOrgchk()))){
                    MpsUser user = mpsUserSvc.findMpsUserById(orgUser.getUserId());
                    MpsOrg org = mpsOrgSvc.findMpsOrgById(orgUser.getOrgId());
                    MpsCheckOrg checkOrg=new MpsCheckOrg();
                    checkOrg.setId(orgUser.getId());
                    checkOrg.setUid(user.getId());
                    checkOrg.setName(user.getName());
                    checkOrg.setOrg(org.getName());
                    //预留申请信息
                    checkOrg.setDescr(orgUser.getDescr());
                    chkList.add(checkOrg);
                }
            }
        }
        view.addObject("chkList",chkList);
        view.addObject("respMsg", respMsg);
        view.setViewName("MpsCheckUserList");
        return view;
    }


    /**
     * 用户申请页面的显示
     * @param respMsg
     * @return
     */
    @GetMapping("/ApplyOrg/goMpsApplyOrgList")
    public ModelAndView goMpsApplyOrgList(@ModelAttribute("respMsg") String respMsg) {
        MpsUser mpsUser = (MpsUser) request.getSession().getAttribute("ADMIN_SESSION");
        //根据用户ID获取用户所有机构
        List<MpsOrgUser> mpsOrgUsersByUid = mpsOrgUserSvc.findMpsOrgUsersByUid(mpsUser.getId());
        //申请页面回显的数据
        List<MpsCheckOrg> checkOrgs=new ArrayList<>();
        //遍历机构
        for (MpsOrgUser mpsOrgUser : mpsOrgUsersByUid) {
            //查询机构详细信息
            MpsOrg mpsOrgById = mpsOrgSvc.findMpsOrgById(mpsOrgUser.getOrgId());
            if("2".equals(String.valueOf(mpsOrgUser.getOrgchk())) || "3".equals(String.valueOf(mpsOrgUser.getOrgchk()))){
                //封装
                MpsCheckOrg checkOrg=new MpsCheckOrg();
                checkOrg.setId(mpsOrgUser.getId());
                checkOrg.setUid(mpsUser.getId());
                checkOrg.setName(mpsUser.getName());
                checkOrg.setOrg(mpsOrgById.getName());
                if("2".equals(String.valueOf(mpsOrgUser.getOrgchk()))){
                    checkOrg.setStatus("等待管理员同意");
                }else {
                    checkOrg.setStatus("被管理员拒绝");
                }
                //预留申请信息
                checkOrg.setDescr(mpsOrgUser.getDescr());
                checkOrgs.add(checkOrg);
            }

        }
        ModelAndView view = new ModelAndView();
        view.addObject("checkOrgs",checkOrgs);
        view.setViewName("MpsApplyOrgList");

        return view;
    }

    /**
     * 用户申请机构添加页面
     * @param respMsg
     * @return
     */
    @GetMapping("/ApplyOrg/goMpsApplyOrgAdd")
    public ModelAndView goMpsApplyOrgAdd(@ModelAttribute("respMsg") String respMsg) {
        MpsUser mpsUser = (MpsUser) request.getSession().getAttribute("ADMIN_SESSION");
        ModelAndView view = new ModelAndView();
        //获取所有机构
        List<MpsOrg> mpsOrgList = mpsOrgSvc.findMpsOrgs(new HashMap<>());
        view.addObject("mpsOrgList",mpsOrgList);
        view.addObject("mpsUser",mpsUser);
        view.setViewName("MpsApplyOrgAdd");
        return view;
    }

    @Authorisation(value = "/MpsOrg/Save")
    @GetMapping("/goMpsOrgAdd")
    public ModelAndView goMpsOrgAdd(@ModelAttribute("respMsg") String respMsg) {
        ModelAndView view = new ModelAndView();
        view.addObject("respMsg", respMsg);
        view.setViewName("MpsOrgAdd");
        return view;
    }

    @Authorisation(value = "/MpsOrg/Save")
    @PostMapping("/Save")
    public String save(RedirectAttributes attr, MpsOrg orgs) {
        if (StringUtils.isEmpty(orgs.getName())) {
            attr.addFlashAttribute("respMsg", "操作添加失败，机构名称不能为空");
            return "redirect:/MpsOrg/goMpsOrgAdd";
        }
        Map<String, Object> map = new HashMap<>();
        List<Condition> conditions = new ArrayList<>();
        conditions.add(ruleBuild("and", "name", "=", orgs.getName(), "S"));
        map.put("conditions", conditions);
        int count = mpsOrgSvc.count(map);
        if (count > 0) {
            attr.addFlashAttribute("respMsg", "操作添加失败，机构名称已存在");
            return "redirect:/MpsOrg/goMpsOrgAdd";
        }
        MpsUser webUser = (MpsUser) request.getSession().getAttribute("ADMIN_SESSION");
        orgs.setCreateOwner(webUser.getId());
        mpsOrgSvc.save(orgs);
        attr.addFlashAttribute("respMsg", "增加机构：" + orgs.getName() + "成功");
        return "redirect:/MpsOrg/goMpsOrgList";
    }

    @Authorisation(value = "/MpsOrg/goMpsOrgList")
    @GetMapping("/Delete")
    public String delete(RedirectAttributes attr, @RequestParam("id") String id) {
        mpsOrgSvc.delete(id);
        attr.addFlashAttribute("respMsg", "删除机构成功");
        return "redirect:/MpsOrg/goMpsOrgList";
    }

    @GetMapping("/Repulse")
    public String repulse(RedirectAttributes attr, @RequestParam("id") String id) {
        mpsOrgUserSvc.repulse(id);
        return "redirect:/MpsOrg/goMpsCheckUserList";
    }


    @Authorisation(value = "/MpsOrg/Update")
    @PostMapping("/Update")
    public String update(RedirectAttributes attr, MpsOrg orgs) {
        if (StringUtils.isEmpty(orgs.getName())) {
            attr.addFlashAttribute("respMsg", "操作修改失败，机构名称不能为空");
            return "redirect:/MpsOrg/goMpsOrgEdit?id=" + orgs.getId();
        }
        Map<String, Object> map = new HashMap<>();
        List<Condition> conditions = new ArrayList<>();
        conditions.add(ruleBuild("and","id","<>", orgs.getId(), "<>"));
        conditions.add(ruleBuild("and","name","=", orgs.getName(), "="));
        map.put("conditions", conditions);
        int count = mpsOrgSvc.count(map);
        if (count > 0) {
            attr.addFlashAttribute("respMsg", "操作修改失败，机构名称已存在");
            return "redirect:/MpsOrg/goMpsOrgEdit?id=" + orgs.getId();
        }
        MpsUser mpsUsers = (MpsUser) request.getSession().getAttribute("ADMIN_SESSION");
        orgs.setModifyOwner(mpsUsers.getId());
        mpsOrgSvc.update(orgs);
        attr.addFlashAttribute("respMsg", "修改机构" + orgs.getName() + "成功");
        return "redirect:/MpsOrg/goMpsOrgList";
}


    /**
     * 用户申请机构保存
     * @param attr
     * @param orgs
     * @param descr
     * @return
     */
    @PostMapping("/ApplyOrg/ApplySave")
    public String ApplySave(RedirectAttributes attr,String[] orgs,String descr) {
        MpsUser webUser = (MpsUser) request.getSession().getAttribute("ADMIN_SESSION");
        if(orgs==null && orgs.length==0){
            attr.addFlashAttribute("respMsg", "机构不能为空");
            return "redirect:/MpsOrg/goMpsApplyOrgList";
        }
        for (String orgId : orgs) {
            mpsOrgUserSvc.applySave(webUser.getId(),orgId,descr);
        }
        return "redirect:/MpsOrg/goMpsOrgList";
    }

    @GetMapping("/AcceptCheck")
    public String ApplySave(RedirectAttributes attr,String id) {
        mpsOrgUserSvc.ApplySave(id);
        attr.addFlashAttribute("respMsg", "已经同意申请");
        return "redirect:/MpsOrg/goMpsCheckUserList";
    }

    /**
     * 根据用户ID获取所有的机构
     * @return
     */
    @GetMapping("/getOrgByUid")
    @ResponseBody
    public  List<MpsOrg> getOrgByUid() {
        MpsUser mpsUser = (MpsUser) request.getSession().getAttribute("ADMIN_SESSION");
        List<MpsOrgUser> mpsOrgUsersByUid = mpsOrgUserSvc.findMpsOrgUsersByUid(mpsUser.getId());
        Iterator<MpsOrgUser> iterator = mpsOrgUsersByUid.iterator();
        while (iterator.hasNext()) {
            MpsOrgUser user = iterator.next();
            if(user.getOrgchk()!=0 || user.getUserchk()!=0){
                iterator.remove();
            }
        }
        List<MpsOrg> mpsOrgList=new ArrayList<>();
        for (MpsOrgUser mpsOrgUser : mpsOrgUsersByUid) {
            MpsOrg mpsOrgById = mpsOrgSvc.findMpsOrgById(mpsOrgUser.getOrgId());
            mpsOrgList.add(mpsOrgById);
        }
        return mpsOrgList;
    }
    /**
     * 改变机构
     * @return
     */
    @GetMapping("/changeOrg")
    public  ModelAndView changeOrg(@RequestParam("orgId") String orgId) {
        request.getSession().setAttribute("Org_SESSION",orgId);
        MpsUser webUser = (MpsUser) request.getSession().getAttribute("ADMIN_SESSION");
        GetFunByUser(webUser.getId(),orgId);
        return  new ModelAndView("redirect:/");
    }

    @PostMapping("/invite")
    @ResponseBody
    public String invite(@RequestParam("id") String id){
        String org_session = (String) request.getSession().getAttribute("Org_SESSION");
        MpsOrgUser mpsOrgUser = mpsOrgUserSvc.findMpsOrgUsersByIdAndOrgId(org_session,id);
        if(mpsOrgUser!=null){
            return "该用户已经存在改机构,或已发出邀请";
        }
        mpsOrgUserSvc.invite(id,org_session);
        return "已发出邀请,请等待用户同意";
    }


}
